<template>
	<view class="newPost">
		<view class="con" v-if="postType==='0'||postType==='3'">
			<view class="title">标题</view>
			<input style="background-color: white;font-size: 30rpx;padding: 20rpx;width: 90%;" v-model="postTitle"
				label="文本" placeholder="请输入标题" />
		</view>
		<view class="con">
			<view class="title">正文 </view>
			<van-field style="width: 100%" v-model:value="postContext" size="large" rows="1" maxlength="200"
				show-word-limit :autosize="{ maxHeight: 80, minHeight: 50 }" type="textarea" placeholder="请输入内容"
				@input="changeValue" />
			<!-- 		<editor id="editor" style="margin: 0 auto;width: 90%; height: 200rpx;" placeholder="请输入内容"
				@input="handleEditorInput" /> -->
			<!-- 	<view class="editorLength">
				{{postContextLength}}/200
			</view> -->
		</view>
		<view class="con">
			<view class="title"> 选择类型 </view>
			<van-radio-group :value="postType" style="width: 100%;overflow: hidden;">
				<van-cell-group>
					<van-cell size="large" v-if="useUser.userInf.role==='jyu_admin'" clickable @click="postType = '0'">
						<template>
							<van-radio icon-size="60rpx" name="0">
								<span style="font-size: 40rpx">公告</span>
							</van-radio>
						</template>
					</van-cell>
					<van-cell size="large" clickable @click="postType = '1'">
						<template>
							<van-radio icon-size="60rpx" name="1">
								<span style="font-size: 40rpx">失物招领</span>
							</van-radio>
						</template>
					</van-cell>
					<van-cell size="large" clickable @click="postType = '2'">
						<template>
							<van-radio icon-size="60rpx" name="2">
								<span style="font-size: 40rpx">意见反馈</span>
							</van-radio>
						</template>
					</van-cell>
					<van-cell size="large" clickable @click="postType = '3'" v-if="myClubList.length">
						<template>
							<van-radio icon-size="60rpx" name="3">
								<span style="font-size: 40rpx">社团活动</span>
							</van-radio>
						</template>
					</van-cell>
				</van-cell-group>
			</van-radio-group>
		</view>
		<view class="con" v-if="postType == '3'">
			<view class="title"> 选择社团 </view>
			<view class="select" @click="intoOptionC"><text>{{currentClub.clubName||`请选择社团`}}</text>
				<view class="conIcon" :class="{inOption:isShowOptionC}">
					<van-icon name="arrow-down" />
				</view>
			</view>
			<view class="conOption" :style="`height:${isShowOptionC?80* myClubList.length:0}rpx`">
				<view class="option" v-for="item in myClubList" :key="item.id" @click="chooseClub(item)">
					{{item.clubName}}
				</view>
			</view>
		</view>
		<view class="con" v-if="isShowTeacher && postType === '3'">
			<view class="title"> 选择指导老师 </view>
			<view class="select" @click="intoOptionT">
				<text>{{teacherList.length===0?'社团暂无指导老师':(currentTeacher?.username || '请选择指导老师')}}</text>
				<view v-if="teacherList.length!==0" class="conIcon" :class="{inOption:isShowOptionT}">
					<van-icon name="arrow-down" />
				</view>
			</view>
			<view class="conOption" :style="`height:${isShowOptionT?80* teacherList.length:0}rpx`">
				<view class="option" v-for="item in teacherList" :key="item.id" @click="chooseTeacher(item)">
					{{item.username}}
				</view>
			</view>
		</view>
		<view class="con">
			<view class="title"> 上传图片 </view>
			<view class="imgList">
				<view v-for="(url, index) in fileList" class="uploadImgs" :key="index">
					<image style="height: 200rpx; width: 200rpx" :src="url" mode="aspectFill"
						@click="previewImage(url, index)"></image>
					<view class="deleteIcon" @click.stop="removeImage(index)">
						<van-icon name="close" />
					</view>
				</view>
				<view v-if="fileList.length < 9" @click="chooseImg" style="border: 2rpx dashed rgba(0, 0, 0, 0.5)"
					class="uploadImgs">
					<van-icon size="100rpx" name="add-o" />
				</view>
			</view>
		</view>
		<view class="con">
			<van-button @click="submitPost" block type="primary" size="large">提交审核</van-button>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		toValue,
		watch,
	} from "vue";
	// import { useCloudStore } from "@/store";
	const fileList = ref([]);
	// const { isInitCloud } = useCloudStore();
	const removeImage = (index) => {
		fileList.value.splice(index, 1);
	};
	import {
		newPost,
		uploadFiles,
		getTeacherByClubId
	} from "@/apis/apis.js";
	import {
		useUserStore
	} from "../../store";

	const useUser = useUserStore()
	const postType = ref(useUser.userInf.role === 'jyu_admin' ? '0' : '1');
	const postTitle = ref("")
	const postContext = ref("");
	const postContextLength = ref(0)
	const MAX_LENGTH = 200;
	const changeValue = (e) => {
		postContextLength.value = e.detail.length
		postContext.value = e.detail;
		console.log(postContext.value.includes('\n'), '\n', e.detail.length);
	}
	const handleEditorInput = (e) => {
		postContextLength.value = e.detail.html.length
		if (e.detail.html.length > MAX_LENGTH) {
			uni.showToast({
				title: `已达到最大字数限制 ${MAX_LENGTH}`,
				icon: 'none'
			});
			// 截取超出部分，确保内容不超过最大长度
			postContext.value = e.detail.html.substring(0, MAX_LENGTH);
		} else {
			postContext.value = e.detail.html;
		}
	};

	// ？为什么不行
	// const chooseImg = () => {
	// 	uni.chooseImage({
	// 		success: (chooseImageRes) => {
	// 			const tempFilePaths = chooseImageRes.tempFilePaths;
	// 			// 遍历选择的图片路径数组，对每一张图片调用uploadFiles接口进行上传
	// 			tempFilePaths.forEach((filePath) => {
	// 				uploadFiles(filePath
	// 					// {
	// 					// 	filePath: filePath,
	// 					// 	name: 'file', // 这里假设后端接收文件的字段名为'file'
	// 					// 	// 如果需要传递额外的formData，可以在这里添加
	// 					// 	// formData: {
	// 					// 	//   'user': 'test'
	// 					// 	// }
	// 					// }
	// 				).then((uploadFileRes) => {
	// 					console.log(uploadFileRes.data);
	// 				}).catch((error) => {
	// 					console.error('上传图片失败', error);
	// 				});
	// 			});
	// 		}
	// 	});
	// };

	const chooseImg = () => {
		const apiUrl = 'https://tww.jyu.edu.cn'
		// const apiUrl = 'https://jyutw.alcy.top'
		uni.chooseImage({
			success: (chooseImageRes) => {
				const tempFilePaths = chooseImageRes.tempFilePaths;
				console.log(tempFilePaths);
				tempFilePaths.forEach((item) => {
					console.log(item);
					uni.compressImage({
						src: item,
						quality: 10,
						success: (compressRes) => {
							// console.log(compressRes.tempFilePath);
							uni.uploadFile({
								url: `${apiUrl}/apis/uploadFiles`, 
								filePath: compressRes.tempFilePath,
								name: 'file',
								header: {
									'Authorization': 'Bearer ' + uni
										.getStorageSync('jyu_token') ||
										useUser
										.token || ''
								},
								success: (uploadFileRes) => {
									const fileUrlTemp =
										apiUrl + JSON
										.parse(
											uploadFileRes.data)
										.filePaths[0]
									fileList.value.push(fileUrlTemp)
								}
							});
						}
					})
				})
			}
		});
	};

	const previewImage = (url, index) => {
		console.log("photoImg", url);
		let imgsArray = fileList.value;
		uni.previewImage({
			current: index,
			urls: imgsArray,
		});
	};


	const submitPost = () => {
		if (!postContext.value.trim()) {
			uni.showToast({
				title: "请输入正文内容",
				icon: "none",
			});
			return;
		}
		if (!postType.value) {
			uni.showToast({
				title: "请选择帖子类型",
				icon: "none",
			});
			return;
		}

		if (postType.value === '0' && postTitle.value === '') {
			uni.showToast({
				title: "请填入公告标题",
				icon: "none",
			});
			return;
		}

		if (postType.value === '3') {
			if (!currentClub.value.id) {
				uni.showToast({
					title: "请选择社团",
					icon: "none",
				});
				return;
			}

			if (!currentTeacher.value.id || teacherList.value.length !== 0) {
				uni.showToast({
					title: "请选择指导老师",
					icon: "none",
				});
				return;
			}
		}
		// if (fileList.value.length === 0) {
		// 	uni.showToast({
		// 		title: "请上传图片",
		// 		icon: "none",
		// 	});
		// 	return;
		// }

		const postData = {
			title: postTitle.value || '',
			content: postContext.value,
			type: postType.value,
			imgUrls: fileList.value,
			clubId: postType.value == '3' ? currentClub.value.id : undefined,
			teacherId: currentTeacher.value.id
		};

		newPost(postData).then(() => {                                                                              
			console.log(postData);
			uni.showToast({
				title: "提交成功",
			});
			setTimeout(() => {
				uni.navigateBack()
				// changeTypeCenter({
				// 	detail: {
				// 		index: 0
				// 	}
			}, 1500)
		}).catch((error) => {
			console.error(error);
			uni.showToast({
				title: "提交失败",
				icon: "none",
			});
		});
	};
	//----
	const currentClub = ref({})
	const currentTeacher = ref({})
	const isShowOptionC = ref(false)
	const isShowOptionT = ref(false)
	const isShowTeacher = ref(false)
	const intoOptionC = () => {
		isShowOptionC.value = !isShowOptionC.value
	}
	const intoOptionT = () => {
		if (teacherList.value.length !== 0) {
			isShowOptionT.value = !isShowOptionT.value
		}
	}
	const chooseClub = (item) => {
		console.log(3213213, item)
		currentClub.value = item
		isShowOptionC.value = false
		isShowTeacher.value = true
	}
	const chooseTeacher = (item) => {
		// console.log(3213213, item)
		currentTeacher.value = item
		isShowOptionT.value = false
	}
	const myClubList = useUser.clubInf.filter(item => item.joinStatus !== 0 && (item.role === 'club_admin' || item.role ===
		'club_teacher'))
	console.log(myClubList)
	const teacherList = ref([])
	// 获取指导老师列表
	const getTeacherList = async (clubId) => {
		try {
			const res = await getTeacherByClubId(clubId)
			if (res.status === 200) {
				teacherList.value = res.data
				console.log(res.data)
			}
		} catch (error) {
			console.error('获取指导老师列表失败:', error)
			uni.showToast({
				title: '获取指导老师列表失败',
				icon: 'none'
			})
		}
	}

	// 清空选择
	const clearChose = (item) => {
		item.value = {}
	}
	watch(() => currentClub.value, (newVal) => {
		if (newVal.id) {
			getTeacherList(newVal.id)
			clearChose(currentTeacher)
		}
	})
</script>

<style lang="less" scoped>
	.newPost {
		width: 100vw;
		padding-top: 10rpx;

		.con {
			width: 100%;
			height: auto;
			min-height: 200rpx;
			padding: 20rpx;
			box-sizing: border-box;
			display: flex;
			flex-direction: column;

			.title {
				font-size: 38rpx;
				padding-bottom: 40rpx;
			}

			.imgList {
				min-width: 80%;
				padding: 10rpx;
				display: flex;
				flex-wrap: wrap;
				gap: 20rpx;
				background-color: white;

				.uploadImgs {
					width: 200rpx;
					height: 200rpx;
					display: inline-block;
					vertical-align: top;
					overflow: hidden;
					background-color: #f7f8fa;
					border-radius: 15rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					box-sizing: border-box;
					position: relative;
					border: 2rpx solid rgba(0, 0, 0, 0.3);

					image {
						width: 100%;
						height: 100%;
						border-radius: 15rpx;
					}

					.deleteIcon {
						position: absolute;
						top: 10rpx;
						right: 10rpx;
						width: 50rpx;
						height: 50rpx;
						background-color: rgba(0, 0, 0, 0.5);
						border-radius: 50%;
						display: flex;
						justify-content: center;
						align-items: center;
						color: white;
					}
				}
			}
		}
	}

	.select {
		height: 80rpx;
		overflow: hidden;
		width: 89%;
		padding: 0 3%;
		background-color: #fff;
		font-size: 38rpx;
		color: grey;
		display: flex;
		align-items: center;
		justify-content: space-between;

		.conIcon {
			transition: all 0.3s;
			height: 80rpx;
			width: 80rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			transform: rotateZ(0);
		}

		.inOption {
			transform: rotateZ(180deg);
		}
	}

	.conOption {
		line-height: 80rpx;
		text-indent: 1.3rem;
		// display: grid;
		// grid-template-rows: 0fr;
		overflow: hidden;
		height: 0;
		transition: all 0.3s;
		background-color: #fff;
		color: black;
		font-size: 38rpx;
		width: 95%;
	}

	.inOption {
		// grid-template-rows: 1fr//没卵用;
		height: 240rpx;
	}
</style>